/*
 * @(#) Meeting.js
 *
 * <br> Copyright:  Copyright (c) 2017
 * <br>
 * <br> @author caijinhuang
 * <br> 2017-11-19 22:15:39
 */

/*
 * @(#) MainBody.js
 *
 * <br> Copyright:  Copyright (c) 2017
 * <br>
 * <br> @author caijinhuang
 * <br> 2017-11-19 22:14:34
 */
import React from 'react';
import Myeditor from "./Myeditor";
import FileUpload from "react-fileupload";
import {
    FormControl,
    FormItem,
    FormGroup,
    From,
    Table,
    Button,
    Modal,
    OverlayTrigger,
    Popover,
    Tooltip,
    DateTime,
    Form,
    Icon,
    ProgressBar,
    TextTip,
    FormSearch,
    InputGroup,
    Textarea,
    DropdownButton,
    MenuItem,
    Panel,
    Paragraph,
    Alert
} from '@share/shareui';
import SelectBody from "./SelectBody";

class MeetingEdit extends React.Component {
    count = 1;

    fileCopy = [];//上传的文件副本
    constructor(props) {
        super(props);
        this.state = {
            /*表单参数*/
            params: {
                meetingId: this.props.id,//会议id
                meetingTitle: '',//会议主题
                meetingPlace: '',//会议地点
                meetingPresenter: this.props.userInfo.userId,//主持人
                meetingContent: '',//会议内容
                meetingDecision: [],//会议决议
                attenderMember: [{userId: this.props.userInfo.userId, state: "A001"}],//所有参会人员
            },

            /*中间参数*/
            addName: "",//添加用户名称
            addState: "",//添加用户状态
            addNameId: "",//添加用户名称ID
            addStateId: "",//添加用户状态ID
            decisionMemberName: this.props.userInfo.nickname,//决议执行人员名称
            decisionState: "",//决议优先级
            allMembers: [],//所有用户成员列表

            /*会议决议内容*/
            decisionTemp: {
                decisionContent: "",//决议内容
                members: [],//决议执行人
                decisionEndTime: "",//截至日期
                priority: "",//决议优先级
            },
            allUsers: [],
            allStates: [],
            allDecisionState: [],
            progress: 0,

            /*组件列表*/
            member: {
                name: this.props.userInfo.nickname,
                department: this.props.userInfo.departmentName,
                email: this.props.userInfo.email,
                state: "正常"
            },
            progressShow: [],//进度条
            decisionComponent: [],//决议列表
            decisionStateComponent: [],//决议优先级状态
            attachmentComponent: [],//附件列表
            hoster: [],//主持人候选人。
            members: [],//成员显示组件
            attenderState: [],//会议出勤状态
            allMemberComponent: [],//所有用户
            fileComponent: [],//上传文件名称回显

            errorInfo:"",
        }
        this.initMeeingBaseInfo();
    }

    /**
     * 初始化基本信息
     */
    initMeeingBaseInfo() {
        let url = "/sharemeeting/meeting/getBaseInfo.do";
        /*异步请求*/
        fetch(url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            credentials: 'include',
        }).then((response) => response.json()) //把response转为json
            .then((responseData) => { // 上面的转好的json
                if (responseData.status === true) {
                    this.initMemberList(responseData.data);
                } else {
                    this.errorInfo(responseData.msg);
                }
            }).catch((error) => {
            this.errorInfo("服务器响应错误");
        })
    }

    /*常量信息初始化*/
    initMemberList(data) {
        this.state.attenderState = [];
        this.state.allMemberComponent = [];
        this.state.allUsers = data.users;
        this.state.allStates = data.attendeState;
        this.state.allDecisionState = data.decisionStates;

        this.state.allMembers = data.users;
        console.log(data.users);
        /*用户列表*/
        for (let i = 0; i < data.users.length; i++) {
            if (data.users[i].roleName !== "super_admin") {
                this.state.allMemberComponent.push(<option value={data.users[i].userId}
                                                           key={data.users[i].nickname}>{data.users[i].nickname}</option>)
            }
        }

        /*主持人候选人*/
        this.state.hoster.push(<option value={this.state.params.attenderMember[0].userId}
                                       key={this.state.params.attenderMember[0].userId}>{this.props.userInfo.nickname}</option>)

        /*决议优先级*/
        for (let i = 0; i < data.decisionStates.length; i++) {
            this.state.decisionStateComponent.push(<option value={data.decisionStates[i].priorityId}
                                                           key={data.decisionStates[i].priorityId}>{data.decisionStates[i].priorityName}</option>);
        }
        // this.state.decisionTemp.priority = data.decisionStates[0].priorityId;
        this.state.decisionState = data.decisionStates[0].priorityName;

        /*出勤状态*/
        for (let i = 0; i < data.attendeState.length; i++) {
            this.state.attenderState.push(<option value={data.attendeState[i].stateId}
                                                  key={data.attendeState[i].attednderState}>{data.attendeState[i].attednderState}</option>);
        }
        /*参会人员列表初始化*/
        this.state.members.push(
            <tr key={this.props.userInfo.userId}>
                <td>{this.state.member.name}</td>
                <td>{this.state.member.department}</td>
                <td>{this.state.member.email}</td>
                <td>
                    <FormControl
                        data-id={this.props.userInfo.userId}
                        componentClass="select" width="200px"
                        onChange={this.changeAttendState.bind(this)}>
                        {this.state.attenderState}
                    </FormControl>
                </td>
                <td></td>
            </tr>);
        this.count = this.count + 1;
        this.setState({members: this.state.members});
    }

    /**
     * 渲染参会人员列表
     */
    renderUserList(memberList) {
        for (let i = 0; i < memberList.length; i++) {
            this.state.allUsers.forEach((value, index, array) => {
                if (value.userId === memberList[i].userId) {
                    this.state.member.department = value.departmentName;
                    this.state.member.email = value.email;
                }
            });
            this.state.members.push(
                <tr key={memberList[i].userId}>
                    <td>{memberList[i].name}</td>
                    <td>{this.state.member.department}</td>
                    <td>{this.state.member.email}</td>
                    <td>
                        <FormControl
                            data-id={memberList[i].userId}
                            componentClass="select" width="200px"
                            onChange={this.changeAttendState.bind(this)}>
                            {this.state.attenderState}
                        </FormControl>
                    </td>
                    <td>
                        {/*<Button onClick={this.selectMember.bind(this)}>添加</Button>*/}
                        <Icon className="fa fa-remove" onClick={this.delMember.bind(this)} data-id={memberList[i].userId}
                              data-flag={memberList[i].userId}/>
                    </td>
                </tr>);
        }
    }

    /**
     * 更改出勤状态
     */
    changeAttendState(e) {
        console.log(e.target.getAttribute("data-id"));
        console.log(e.target.value);
        console.log(this.state.params.attenderMember);
        this.state.params.attenderMember.forEach((value, index, array) => {
            if (value.userId === e.target.getAttribute("data-id")) {
                value.state = e.target.value;
            }
        })
        console.log(this.state.params.attenderMember);
    }

    /**
     * 添加参会人员
     */
    addPerson() {
        let datalist = this.refs.selectBody.getList();
        for (let i = 0; i < datalist.length; i++) {
            this.state.params.attenderMember.push({userId: datalist[i].userId, state: this.state.allStates[0].stateId});
            this.state.hoster.push(<option value={datalist[i].userId} key={datalist[i].userId}>{datalist[i].name}</option>)
        }
        this.renderUserList(datalist);
        this.close();
    }

    /**
     * 删除参会人员
     * @param e
     */
    delMember(e) {
        /**
         * filter过滤掉不符合删除条件的元素保存下来
         * @type {Array.<*>}
         */
        const mlist = this.state.members.filter((value, index) => {
            if (value.key !== e.target.getAttribute("data-id")) {
                return value
            }
        });
        this.state.params.attenderMember = this.state.params.attenderMember.filter((value, index) => {
            console.log(value.userId + "|" + e.target.getAttribute("data-flag"));
            if (value.userId !== e.target.getAttribute("data-flag")) {
                return value;
            }
        });
        this.state.hoster = this.state.hoster.filter((value, index) => {
            console.log(value.key + "|" + e.target.getAttribute("data-flag"));
            if (value.key !== e.target.getAttribute("data-flag")) {
                return value;
            }
        });
        console.log(this.state.params.attenderMember);
        this.setState({members: mlist});
        console.log(this.state.hoster);
    }

    /*获取成员列表*/
    getMemberList() {
        return this.state.params.attenderMember;
    }

    /*决议添加界面*/
    addDecision() {
        this.setState({showDecision: true});
    }

    /*用户选择界面*/
    selectMember() {
        this.setState({showModal: true});
    }

    /*错误提示*/
    errorInfo(info){
        this.state.errorInfo = info;
        this.setState({showTip: true});
    }

    /*保存会议决议*/
    saveDecision() {
        let memberList = this.refs.selectMemberList.getList();//获取选中的成员
        console.log(memberList);
        if (memberList.length === 0) {
            alert("还未添加执行人");
        } else {
            if (this.state.decisionTemp.decisionContent.length !== 0 && this.state.decisionTemp.decisionEndTime.length !== 0) {
                if (this.state.decisionComponent.length === 0) {
                    this.state.decisionComponent.push(
                        <tr key={this.count}>
                            <th>优先级</th>
                            <th>决议内容</th>
                            <th>截止</th>
                            <th>负责人</th>
                            <th>操作</th>
                        </tr>
                    );
                }
                this.count = this.count + 1;
                let carryMemebr = "";
                this.state.decisionTemp.members = [];//清空数组;
                for (let i = 0; i < memberList.length; i++) {
                    this.state.decisionTemp.members.push(memberList[i].userId);
                    carryMemebr = carryMemebr + memberList[i].name;
                    if (i !== memberList.length - 1) {
                        carryMemebr = carryMemebr + "、";
                    }
                }
                this.state.decisionComponent.push(
                    <tr key={this.count}>
                        <td>{this.state.decisionState !== "" ? this.state.decisionState : this.state.allDecisionState[0].priorityName}</td>
                        <td>{this.state.decisionTemp.decisionContent}</td>
                        <td>{this.state.decisionTemp.decisionEndTime}</td>
                        <td>{carryMemebr}</td>
                        <td>
                            <Icon className="fa fa-remove" onClick={this.removeDecision.bind(this)} data-id={this.count}
                                  data-content={this.state.decisionTemp.decisionContent}/>
                        </td>
                    </tr>
                );

                // 将决议存入表单
                console.log(this.state.decisionTemp.priority);
                console.log(this.state.allDecisionState[0].priorityId)
                this.state.params.meetingDecision.push({
                                                           decisionContent: this.state.decisionTemp.decisionContent,//决议内容
                                                           members: this.state.decisionTemp.members,//决议执行人
                                                           decisionEndTime: this.state.decisionTemp.decisionEndTime,//截至日期
                                                           priority: this.state.decisionTemp.priority !== ""
                                                               ? this.state.decisionTemp.priority
                                                               : this.state.allDecisionState[0].priorityId,//决议优先级
                                                       });
                console.log(this.state.params.meetingDecision);
                //清空文本内容
                this.state.decisionTemp.decisionContent = "";
                this.state.decisionTemp.decisionEndTime = "";
                this.state.decisionTemp.priority = "";
                this.state.decisionState = "";
                console.log(this.state.params);
                this.setState({showDecision: false});
            } else {
                alert("内容不能为空");
            }
        }
    }

    /*删除决议*/
    removeDecision(e) {
        /*删除对应的显示组件*/
        this.state.decisionComponent = this.state.decisionComponent.filter((v, i) => {
            if (v.key !== e.target.getAttribute("data-id")) {
                return v;
            }
        });
        /*删除对应的决议参数*/
        this.state.params.meetingDecision = this.state.params.meetingDecision.filter((v, i) => {
            if (v.decisionContent !== e.target.getAttribute("data-content")) {
                console.log(v.decisionContent + "|" + e.target.getAttribute("data-content"))
                return v;
            }
        });
        console.log(this.state.params.meetingContent);
        if (this.state.decisionComponent.length === 1) {
            this.state.decisionComponent = [];
        }
        /*更新组件*/
        this.close();
    }

    /*渲染组件列表*/
    renderFileList(resp) {
        console.log(resp);
        let fileList = resp.data;
        for(let name in fileList){
            this.state.fileComponent.push(
                <tr className="item_list" key={fileList[name]}>
                    <Icon className="fa fa-file ui-icon-custom2"/>
                    {name}
                    <Icon className="fa fa-remove ui-right"
                          data-id={fileList[name]}
                          data-name={name}
                          onClick={(e) => {
                              this.state.fileComponent =  this.state.fileComponent.filter( (value, index) => {
                                  if (value.key !== e.target.getAttribute("data-id")) {
                                      return value;
                                  }
                                  this.deleteFile(e.target.getAttribute("data-name"),value.key);
                              });
                              this.close();
                          }}/>
                </tr>);
        }
        this.close();
    }

    /*删除附件*/
    deleteFile(fileName,fileId){
        let url = "/sharemeeting/meeting/deletfile.do";
        /*异步请求*/
        fetch(url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            body: JSON.stringify({fileName:fileName,fileId:fileId})
        }).then((response) => response.json()) //把response转为json
            .then((responseData) => { // 上面的转好的json
                if (responseData.status !== true) {
                    alert(responseData.msg);
                    this.errorInfo()
                }
            }).catch((error) => {
            this.errorInfo("服务器无响应");
        })
    }

    /**
     * 关闭弹出层
     */
    close() {
        this.setState({showModal: false, showDecision: false, showTip:false});
    }

    /*检查提交内容*/
    commitMeeting() {
        this.state.params.meetingContent = this.refs.myEditor.getContents();
        if (this.state.params.meetingTitle === "" || this.state.params.meetingPlace === "" || this.state.params.meetingContent === "") {
            console.log(this.state.params.meetingTitle + "|" + this.state.params.meetingPlace + "|" + this.state.params.meetingContent)
            alert("内容不完整，请补充完整");
        } else if (this.fileCopy.length !== 0) {
            alert(("有附件未上传，点击上传？"));
        } else if (this.state.params.meetingDecision.length === 0) {
            if (window.confirm("还未添加决议内容,确定要提交吗？") === true) {
                this.postInfo();
            }
        } else {
            this.postInfo();
        }

    }

    /*提交请求*/
    postInfo() {
        let url = "/sharemeeting/meeting/savaMeeting.do";
        /*异步请求*/
        fetch(url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            body: JSON.stringify(this.state.params)
        }).then((response) => response.json()) //把response转为json
            .then((responseData) => { // 上面的转好的json
                if (responseData.status === true) {
                    alert(responseData.msg);
                    this.state.params.meetingId = responseData.data.id;
                    window.location.reload();
                } else {
                    alert(responseData.msg);
                }
            }).catch((error) => {
            alert("与服务器失联了");
        })
    }

    render() {
        //文件上传操作
        let option = {
            baseUrl: "/sharemeeting/meeting/upload.do",
            param: {//作为get的附加参数
                meetingId: this.state.params.meetingId,
            },
            accept: '.zip, .png, .jpg',//限制文件类型后缀
            multiple: true,//多文件上传
            numberLimit: 5,//限制用户选择数量
            chooseAndUpload: true,//选中并上传
            withCredentials: true,//与 xhr.withCredentials 一致,
            fileFieldName(file) {return "file"},//设置文件名称作为参数
            //上传前的检查
            beforeUpload: function (files, mill) {
                // if(typeof files == '.zip') return true;
                if (files.length === 0) {
                    alert("没有可上传的文件");
                    return false;
                }
                let allSize = 0;
                for (let i = 0; i < files.length; i++) {
                    console.log(files[i].size);
                    allSize = allSize + files[i].size;
                }
                if (allSize < 1024 * 1024 * 500) {
                    return true
                }
                alert("文件大小大于500M无法上传");
                return true;
            },
            //上传成功
            uploadSuccess : this.renderFileList.bind(this),
        };

        return (
            <div>
                <div className="row-control">
                    <Panel.Body full>
                        <Form pageType="addPage">
                            <Form.Table>
                                <Form.Tr>
                                    <Form.Label required>会议标题</Form.Label>
                                    <Form.Content>
                                        <FormControl type="text"
                                                     value={this.state.params.meetingTitle}
                                                     placeholder="请输入会议标题"
                                                     onChange={(e) => {
                                                         this.state.params.meetingTitle = e.target.value;
                                                         this.setState({addStateId: ""})
                                                     }}
                                        />
                                    </Form.Content>
                                    <Form.Label rowSpan="2" required>主持人</Form.Label>
                                    <Form.Content rowSpan="2">
                                        <FormControl
                                            componentClass="select" width="200px"
                                            onChange={(e) => {
                                                this.state.params.meetingPresenter = e.target.value
                                            }}>
                                            {this.state.hoster}
                                        </FormControl>
                                        <Paragraph bsStyle="info"><i className="fa fa-info-circle text-info"/>主持人从参会人员中产生，需要先添加参会人员，否则默认当前用户为主持人</Paragraph>
                                    </Form.Content>
                                </Form.Tr>
                                <Form.Tr>
                                    <Form.Label required>会议地点</Form.Label>
                                    <Form.Content>
                                        <InputGroup>
                                            <FormControl type="text"
                                                         value={this.state.params.meetingPlace}
                                                         placeholder="请输入会议地点"
                                                         onChange={(e) => {
                                                             this.state.params.meetingPlace = e.target.value;
                                                             this.setState({addStateId: ""});
                                                         }}/>
                                            <InputGroup.Button>
                                                <DropdownButton
                                                    bsSize="small" id="bg-nested-dropdown" pullRight
                                                    title="选择"
                                                    onSelect={(any, event) => {
                                                        this.state.params.meetingPlace = event.target.innerHTML;
                                                        this.setState({addStateId: ""});
                                                    }}
                                                >
                                                    <MenuItem key="1">408小会议室</MenuItem>
                                                    <MenuItem key="2">408大会议室</MenuItem>
                                                    <MenuItem key="3">508大会议室</MenuItem>
                                                </DropdownButton>
                                            </InputGroup.Button>
                                        </InputGroup>
                                    </Form.Content>
                                </Form.Tr>
                            </Form.Table>
                        </Form>
                    </Panel.Body>
                </div>


                <div className="mylist-group">
                    <Panel.Head title="参会人员 ">
                        <Icon className="fa-plus-square-o custom-style" onClick={this.selectMember.bind(this)}/>
                    </Panel.Head>
                    <div className="ui-table-custom3">
                        <Table>
                            <tbody>
                            {this.state.members}
                            </tbody>
                        </Table>
                    </div>
                </div>

                <div className="mylist-group">
                    <Panel.Head title="会议内容"/>
                    <Myeditor ref="myEditor"/>
                </div>


                <div className="mylist-group">
                    <Panel.Head title="决议"><Icon className="fa-plus-square-o custom-style"
                                                 onClick={this.addDecision.bind(this)}/></Panel.Head>
                    <div className="ui-table-custom3">
                        <Table style={{textAlign: "center"}} className="ui-table-custom">
                            <tbody>
                            {this.state.decisionComponent}
                            </tbody>
                        </Table>
                    </div>
                </div>
                <div className="mylist-group">
                    <Panel.Head title="附件">
                        <FileUpload options={option} ref="File-Upload">
                            <Icon className="fa-plus-square-o custom-style"  ref="chooseAndUpload"/>
                            {/*<Icon className="fa-cloud-upload custom-style" bsSize="lg" ref="uploadBtn"/>*/}
                            {this.state.progressShow}
                        </FileUpload>
                    </Panel.Head>
                    <div className="ui-table-custom3">
                        <Table striped condensed hover>
                            <tbody>
                            {this.state.fileComponent}
                            </tbody>
                        </Table>
                    </div>
                    <div className="mylist-group">
                        <div>
                            <Table style={{textAlign: "center"}}>
                                <tr>
                                    <Button type="button" bsStyle="success" onClick={this.commitMeeting.bind(this)}>保存并发布</Button>
                                </tr>
                            </Table>
                        </div>
                    </div>
                </div>


                {/*弹出层：出勤人员编辑*/}
                <Modal show={this.state.showModal} onHide={this.close.bind(this)}>
                    <Modal.Header closeButton>
                        <Modal.Title id="contained-modal-title-lg">请从左边选择参会人员添加到右边</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <SelectBody option={this.getMemberList.bind(this)} listCell={this.state.allMembers}
                                    selectedList={this.state.params.attenderMember} ref="selectBody"/>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button onClick={this.close.bind(this)}>取消</Button>
                        <Button onClick={this.addPerson.bind(this)}>确定</Button>
                    </Modal.Footer>
                </Modal>

                {/*弹出层：会议决议编辑*/}
                <Modal show={this.state.showDecision} onHide={this.close.bind(this)}>
                    <Modal.Header closeButton>
                        <Modal.Title id="contained-modal-title-lg">会议决议</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Panel.Body full>
                            <Form pageType="addPage">
                                <Form.Table>
                                    <Form.Tr>
                                        <Form.Label required>截止：</Form.Label>
                                        <Form.Content colSpan="2">
                                            <DateTime input1Props={{
                                                id: 'time', changeDate: (val, ev) => {
                                                    this.state.decisionTemp.decisionEndTime = val;
                                                }
                                            }}/>
                                        </Form.Content>
                                        <Form.Label required>优先级：</Form.Label>
                                        <Form.Content>
                                            <FormControl
                                                componentClass="select" width="200px"
                                                onChange={(e) => {
                                                    this.state.decisionState = e.nativeEvent.target.selectedOptions[0].label;
                                                    this.state.decisionTemp.priority = e.target.value;
                                                    console.log(this.state.params.meetingDecision)
                                                }}>
                                                {this.state.decisionStateComponent}
                                            </FormControl>
                                        </Form.Content>
                                    </Form.Tr>
                                    <Form.Tr>
                                        <Form.Label required>执行人员：</Form.Label>
                                        <Form.Content colSpan="4">
                                            <SelectBody remain="true" option={this.getMemberList.bind(this)}
                                                        listCell={this.state.allMembers} selectedList={this.state.params.attenderMember}
                                                        ref="selectMemberList"/>
                                        </Form.Content>
                                    </Form.Tr>
                                    <Form.Tr>
                                        <Form.Label required>决议内容：</Form.Label>
                                        <Form.Content colSpan="4">
                                            <Textarea rows="4"
                                                      value={this.state.decisionTemp.decisionContent}
                                                      placeholder="请输入会议决议内容"
                                                      onChange={(e) => {
                                                          this.state.decisionTemp.decisionContent = e.target.value;
                                                          this.setState();
                                                      }}/>
                                        </Form.Content>
                                    </Form.Tr>
                                </Form.Table>
                            </Form>
                        </Panel.Body>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button onClick={this.close.bind(this)}>取消</Button>
                        <Button onClick={this.saveDecision.bind(this)}>确定</Button>
                    </Modal.Footer>
                </Modal>

                <Modal bsSize="small" show={this.state.showTip} onHide={this.close.bind(this)}>
                    <Modal.Header closeButton>
                        <Modal.Title>错误提示</Modal.Title>
                    </Modal.Header>
                    <Modal.Body validationState="success" message="网络请求错误">
                        {this.state.errorInfo}
                    </Modal.Body>
                    <Modal.Footer>
                        <Button onClick={this.close.bind(this)}>关闭</Button>
                    </Modal.Footer>
                </Modal>
            </div>
        );
    }
}

export default MeetingEdit
